﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using SageKing.Database.EF.Features;
using SageKing.Database.Features;

namespace SageKing.Extensions;

public static class ModuleExtensions
{
    public static IModule UseSageKingDatabaseEF(this IModule module, Action<SageKingDatabaseEFFeature>? configure = default)
    {
        module.Configure<SageKingDatabaseEFFeature>(feature =>
        {
            configure?.Invoke(feature);
        });

        module.UseIceMediatR(o => o.MediatRServiceConfiguration += a =>
        {
            a.RegisterServicesFromAssembly(typeof(SageKingDatabaseEFFeature).Assembly);
        });
        return module;
    }

    public static IServiceCollection AddTemplateStore<TContext>(this IServiceCollection services,
Action<TemplateStoreOptions> storeOptionsAction = null)
where TContext : DbContext, ITemplateContext
    {
        var options = new TemplateStoreOptions();
        services.AddSingleton(options);
        storeOptionsAction?.Invoke(options);

        if (options.ResolveDbContextOptions != null)
        {
            services.AddDbContext<TContext>(options.ResolveDbContextOptions);
        }
        else
        {
            services.AddDbContext<TContext>(dbCtxBuilder =>
            {
                options.TemplateContext?.Invoke(dbCtxBuilder);
            });
        }

        services.AddScoped<ITemplateContext, TContext>();

        services.AddScoped<TemplateBaseService<TemplateBase, long>>();
        services.AddScoped<TemplateBaseService<TemplateConfigBase, long>>();
        services.AddScoped<TemplateBaseService<TenantTemplateDataBase, long>>();

        return services;
    }
}
